<template>
  <div class="ad-proportion">
    <div class="header">
      <h3>广告分佣比例配置</h3>
      <p>配置各角色的广告分佣比例，总比例不能超过100%</p>
    </div>

    <el-form :model="form" :rules="rules" ref="form" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="总公司比例" prop="headquarters">
            <el-input-number
              v-model="form.headquarters"
              :min="0"
              :max="1"
              :step="0.01"
              :precision="2"
              style="width: 200px"
            />
            <span class="unit">%</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="区域代理比例" prop="agent">
            <el-input-number
              v-model="form.agent"
              :min="0"
              :max="1"
              :step="0.01"
              :precision="2"
              style="width: 200px"
            />
            <span class="unit">%</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商家比例" prop="merchant">
            <el-input-number
              v-model="form.merchant"
              :min="0"
              :max="1"
              :step="0.01"
              :precision="2"
              style="width: 200px"
            />
            <span class="unit">%</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户比例" prop="user">
            <el-input-number
              v-model="form.user"
              :min="0"
              :max="1"
              :step="0.01"
              :precision="2"
              style="width: 200px"
            />
            <span class="unit">%</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button type="primary" @click="handleSave" :loading="loading">保存配置</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="summary">
      <el-alert
        :title="`当前总比例: ${totalPercentage}%`"
        :type="totalPercentage > 100 ? 'error' : (totalPercentage === 100 ? 'success' : 'warning')"
        :description="totalPercentage > 100 ? '总比例不能超过100%' : (totalPercentage === 100 ? '比例配置正确' : '总比例不足100%')"
        show-icon
        :closable="false"
      />
    </div>
  </div>
</template>

<script>
import { getProportionList, addProportion, editProportion } from '@/api/aggregation'

export default {
  name: 'AdProportion',
  data() {
    return {
      loading: false,
      form: {
        headquarters: 0.4,  // 40%
        agent: 0.3,         // 30%
        merchant: 0.2,      // 20%
        user: 0.1           // 10%
      },
      rules: {
        headquarters: [
          { required: true, message: '请输入总公司比例', trigger: 'blur' },
          { type: 'number', min: 0, max: 1, message: '比例范围为0-1', trigger: 'blur' }
        ],
        agent: [
          { required: true, message: '请输入区域代理比例', trigger: 'blur' },
          { type: 'number', min: 0, max: 1, message: '比例范围为0-1', trigger: 'blur' }
        ],
        merchant: [
          { required: true, message: '请输入商家比例', trigger: 'blur' },
          { type: 'number', min: 0, max: 1, message: '比例范围为0-1', trigger: 'blur' }
        ],
        user: [
          { required: true, message: '请输入用户比例', trigger: 'blur' },
          { type: 'number', min: 0, max: 1, message: '比例范围为0-1', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    totalPercentage() {
      return ((this.form.headquarters + this.form.agent + this.form.merchant + this.form.user) * 100).toFixed(2)
    }
  },
  mounted() {
    this.loadProportionConfig()
  },
  methods: {
    async loadProportionConfig() {
      try {
        Logger.log('加载广告分佣配置...')
        const response = await getProportionList()
        Logger.log('分佣比例API响应:', response)

        if (response.code === 0) {
          // 根据API文档，type=1表示广告分佣
          const adConfigs = response.data.filter(item => item.type === 1)
          Logger.log('广告分佣配置数据:', adConfigs)

          // 根据roleType设置对应的比例
          adConfigs.forEach(config => {
            switch (config.roleType) {
              case 5: // 总公司
                this.form.headquarters = config.proportion || 0.4
                break
              case 4: // 区域代理
                this.form.agent = config.proportion || 0.3
                break
              case 3: // 商家
                this.form.merchant = config.proportion || 0.2
                break
              case 1: // c端用户
                this.form.user = config.proportion || 0.1
                break
            }
          })
        }
      } catch (error) {
        Logger.error('加载分佣配置失败:', error)
        // 使用默认配置
      }
    },

    async handleSave() {
      if (this.totalPercentage > 100) {
        this.$message.error('总比例不能超过100%')
        return
      }

      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.loading = true
          try {
            // 根据API文档，需要分别保存每个角色的配置
            const configs = [
              { roleType: 5, proportion: this.form.headquarters }, // 总公司
              { roleType: 4, proportion: this.form.agent },        // 区域代理
              { roleType: 3, proportion: this.form.merchant },     // 商家
              { roleType: 1, proportion: this.form.user }          // c端用户
            ]

            Logger.log('保存广告分佣配置:', configs)

            // 保存每个角色的配置
            for (const config of configs) {
              const configData = {
                type: 1, // 1=广告分佣
                roleType: config.roleType,
                proportion: config.proportion
              }

              Logger.log('保存配置项:', configData)
              const response = await addProportion(configData)
              Logger.log('保存响应:', response)

              if (!response.data || !response.data.code === 0) {
                this.$message.error(response.data?.msg || '保存失败')
                return
              }
            }

            this.$message.success('广告分佣配置保存成功')
          } catch (error) {
            Logger.error('保存配置失败:', error)
            this.$message.error('保存配置失败')
          } finally {
            this.loading = false
          }
        }
      })
    },

    handleReset() {
      this.form = {
        headquarters: 0.4,
        agent: 0.3,
        merchant: 0.2,
        user: 0.1
      }
    }
  }
}
</script>

<style scoped>
.ad-proportion {
  padding: 20px;
}

.header {
  margin-bottom: 30px;
}

.header h3 {
  margin: 0 0 10px 0;
  color: #303133;
}

.header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.unit {
  margin-left: 10px;
  color: #909399;
}

.summary {
  margin-top: 30px;
}
</style>
